package com.example.nettydemo.BIOServer;

import com.sun.org.apache.xerces.internal.impl.io.UTF8Reader;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.util.concurrent.*;
import java.net.Socket;
//启动telnet客户端  控制面板-》程序-》启动或关闭Windows功能-》telnet客户端 勾选
//cmd
//telnet 127.0.0.1 端口号
//ctrl+]
//send 发送的信息
public class Server服务端 {
    public static void main(String[] args) throws IOException {
        ExecutorService executorService =  new ThreadPoolExecutor(
                2,
                5,
                2L,//线程存活时间
                TimeUnit.SECONDS,//时间单位
                new LinkedBlockingDeque<>(3), //阻塞队列
                Executors.defaultThreadFactory(),//表示生成线程池中工作线程的线程工厂  用于创建线程  一般默认
                new ThreadPoolExecutor.DiscardOldestPolicy()//拒绝策略  当阻塞队列满了  工作线程大于等于最大线程数时触发
        );
        ServerSocket serverSocket = new ServerSocket(5555);
        while (true){
            Socket socket = serverSocket.accept();
            System.out.println("连接了一个客户");
            executorService.execute(()->Input(socket));
        }

    }

    public static void Input(Socket socket){
        byte[] bytes = new byte[1024];
        InputStream inputStream = null;

        try {
            System.out.println("启动"+Thread.currentThread().getName()+"线程   ");
            inputStream = socket.getInputStream();
            while (true) {
                int read = inputStream.read(bytes);
                if (read!=-1){
                    System.out.println(new String(bytes,0,read));
                }else {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                inputStream.close();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
